package com.mate.cloud.rocketmq;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mate.cloud.domian.OrderMessage;
import com.mate.cloud.domian.OrderMessageDTO;
import com.mate.cloud.mapper.OrderMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 异步补偿服务
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/8/12 16:07
 * @updateUser: MI
 * @updateTime: 2025/8/12 16:07
 * @updateRemark: 修改内容
 * @version: 1.0
 */
@Slf4j
@Service
public class CompensationService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderMessageMapper orderMessageMapper;

    // 定时检查未完成订单（补偿逻辑）
    @Scheduled(fixedDelay = 60000)
    public void compensateFailedOrders() {
        LambdaQueryWrapper<OrderMessage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderMessage::getStatus, "CREATED");
        List<OrderMessage> unfinishedOrders = orderMessageMapper.selectList(lambdaQueryWrapper);
        unfinishedOrders.forEach(order -> {
            OrderMessageDTO message = new OrderMessageDTO();
            message.setOrderId(order.getOrderId());
            message.setAction("CHECK_COMPENSATION");
            rocketMQTemplate.syncSend("compensation-topic", message);
            log.info("触发补偿检查: {}", order.getOrderId());
        });
    }
}
